package com.happiness.gateway.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.happiness.base.bean.JwtUserInfo;
import com.happiness.base.bean.UserCacheInfo;
import com.happiness.base.utils.redis.RedisUtil;
import com.happiness.gateway.service.UserCacheService;
import com.happiness.gateway.utils.JwtTokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

@Component
public class UserCacheServiceImpl implements UserCacheService {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private JwtTokenUtils jwtTokenUtils;

    @Override
    public String cacheUser(UserCacheInfo cacheInfo, HttpServletRequest request) {
        String redisToken = IdUtil.randomUUID();
        JwtUserInfo jwtUserInfo = JwtUserInfo.builder()
                .redisToken(redisToken)
                .build();
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(checkOrAssembling(request, false, jwtUserInfo));
        return jwtTokenUtils.createToken(cacheInfo.getUsername(),stringObjectMap);
    }



    /**
     * 装配或加载浏览器信息
     * @param request 请求信息
     * @param isCheck 是否校验信息？否则为装配
     * @param jwtUserInfo 用户信息
     * @return 是否校验或装配成功
     * */
    private Boolean checkOrAssembling(HttpServletRequest request,boolean isCheck,JwtUserInfo jwtUserInfo){
        UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        String ipaddr = ServletUtil.getClientIP(request);
        String engineInfo = userAgent.getEngine() + userAgent.getEngineVersion();
        String browser = userAgent.getBrowser().toString();
        String os = userAgent.getOs().toString();
        if (isCheck){
            return Objects.equals(ipaddr,jwtUserInfo.getIpaddr()) &&
                    Objects.equals(engineInfo,jwtUserInfo.getEngineInfo()) &&
                    Objects.equals(os,jwtUserInfo.getOs()) &&
                    Objects.equals(browser,jwtUserInfo.getBrowser());
        }else {
            jwtUserInfo.setEngineInfo(engineInfo);
            jwtUserInfo.setIpaddr(ipaddr);
            jwtUserInfo.setOs(os);
            jwtUserInfo.setBrowser(browser);
        }
        return true;
    }
}
